package airthmetic.exercise.dp;

public class _188_买卖股票的最佳时机IV {
    // 普通动态规划
    public static int maxProfit(int maxK, int[] prices) {
        int n = prices.length;
        int[][][] dp = new int[n][maxK + 1][2];
        for(int i=0; i<n; i++){
            for(int k=1; k<=maxK; k++){
                if(i==0){
                    dp[i][k][0] = 0;
                    dp[i][k][1] = -prices[i];
                    continue;
                }
                dp[i][k][0] = Math.max(dp[i-1][k][0], dp[i-1][k][1] + prices[i]);
                dp[i][k][1] = Math.max(dp[i-1][k][1], dp[i-1][k-1][0] - prices[i]);
            }
        }

        return dp[n-1][maxK][0];
    }

    // 状态压缩动态规划
    public static int maxProfit2(int maxK, int[] prices) {

        int n = prices.length;
        int[][] dp = new int[maxK + 1][2];
        for (int i = 0; i < n; i++) {
            for (int k = 1; k <=maxK; k++) {
                if (i == 0) {
                    dp[k][0] = 0;
                    dp[k][1] = -prices[i];
                    continue;
                }
                dp[k][0] = Math.max(dp[k][0], dp[k][1] + prices[i]);
                dp[k][1] = Math.max(dp[k][1], dp[k - 1][0] - prices[i]);
            }
        }
        return dp[maxK][0];
    }

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());
        System.out.println(maxProfit(5, new int[]{7,5,6,3,1,8,9,4,6,3,23,3,5,631,4,21,23,123,213,12,312,1}));
        System.out.println(maxProfit2(5, new int[]{7,5,6,3,1,8,9,4,6,3,23,3,5,631,4,21,23,123,213,12,312,1}));
        System.out.println(System.currentTimeMillis());
    }
}
